package com.bnlr.lrparking.appui.carport;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.base.BaseJavaBean;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.model.AddStallTypeBean;
import com.bnlr.lrparking.model.CarPlaceTypeMode;
import com.bnlr.lrparking.appui.publish.SelectParkingActivity;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.appui.carport.bean.CarportShareResultBean;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.lrparking.widget.boarddialog.KeyBoardDialog;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.bnlr.nohttp.CustomJavaHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 车位共享页面
 */
public class CarportShareActivity extends BaseActivity {

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.publish_housing)
    ClearEditText publishHousing;
    @BindView(R.id.publish_park_dq)
    TextView publishParkDq;
    @BindView(R.id.publish_place_number)
    ClearEditText publishPlaceNumber;
    @BindView(R.id.publish_place_floor)
    ClearEditText publishPlaceFloor;
    @BindView(R.id.type_choose)
    TextView typeChoose;
    @BindView(R.id.et_name)
    ClearEditText etName;
    @BindView(R.id.man)
    RadioButton man;
    @BindView(R.id.rb_woman)
    RadioButton rbWoman;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.ll_share_apply)
    LinearLayout llShareApply;
    @BindView(R.id.ll_share_result)
    LinearLayout llShareResult;
    private String username, publishPhone;
    private Double lat,lng;
    private String cityName,areaName;
    private OptionsPickerView pvCustomOptions;
    private ArrayList<ArrayList<CarPlaceTypeMode>> carType2 = new ArrayList<>();
    private ArrayList<CarPlaceTypeMode> carType1 = new ArrayList<>();
    private String carPlaceId;
    private String provinceName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carport_share);
        ButterKnife.bind(this);
        tvNavTitle.setText("车位共享");
        username = AppConfig.getInstance().getString("userName", "");
        publishPhone = username;
        if (!username.equals("")) {
            tvPhone.setText(username.substring(0, 3) + "****" + username.substring(7));
        }
        getCarportShareResult();
    }

    /**
     * 获取共享提交结果
     */
    private void getCarportShareResult() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.BASE_JAVA_URL+"system/getParkingShareList", LrConstant.POST);
            // 添加到请求队列+
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomJavaHttpListener<CarportShareResultBean>(this, true, CarportShareResultBean.class) {
                        @Override
                        public void doWork(CarportShareResultBean data, int code) {
                            if (data.getModel().getData().size() > 0) {
                                llShareResult.setVisibility(View.VISIBLE);
                            } else {
                                llShareApply.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onFinally(String obj, int code, boolean isSucceed) throws JSONException {
                            super.onFinally(obj, code, isSucceed);
                            if (code != 0) {
                                llShareApply.setVisibility(View.VISIBLE);
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    @OnClick({R.id.publish_park_dq, R.id.tv_car_share_submit,R.id.tv_phone,R.id.type_choose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.publish_park_dq:
                startActivityForResult(new Intent(this,SelectParkingActivity.class)
                        ,1007);
                break;
            case R.id.tv_car_share_submit:
                if (TextUtils.isEmpty(publishHousing.getText().toString())) {
                    ToastUtils.showShort("请选择小区");
                    return;
                }
                if (TextUtils.isEmpty(publishParkDq.getText().toString())) {
                    ToastUtils.showShort("请选择停车场地址");
                    return;
                }
                if (TextUtils.isEmpty(publishPlaceNumber.getText().toString())) {
                    ToastUtils.showShort("请填写车位编号");
                    return;
                }
                if (TextUtils.isEmpty(publishPlaceFloor.getText().toString())) {
                    ToastUtils.showShort("请填写楼层");
                    return;
                }
                if (TextUtils.isEmpty(typeChoose.getText().toString())) {
                    ToastUtils.showShort("请选择车位类型");
                    return;
                }
                if (TextUtils.isEmpty(etName.getText().toString())) {
                    ToastUtils.showShort("请填写姓名");
                    return;
                }
                submitShareInfo();
                break;
            case R.id.type_choose:
                if (carType1.size() > 0) {
                    initCustomOptionPicker();
                } else {
                    getCarPlaceType();
                }
                break;
            case R.id.tv_phone:
                KeyBoardDialog dialog = new KeyBoardDialog(this, publishPhone);
                dialog.setOnDialogResultListener(new KeyBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String result) {
                        if (result.equals("some")) {
                            ToastUtils.showShort("此手机号无需再次验证");
                        } else if (!result.equals("fail")) {
                            publishPhone = result;
                            tvPhone.setText(publishPhone.substring(0, 3) + "****" + publishPhone.substring(7));
                        }
                    }
                });
                dialog.show();
                break;
            default:
                break;
        }
    }

    private void submitShareInfo() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.BASE_JAVA_URL+"system/saveParkingShare", LrConstant.POST);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("spaceType", carPlaceId);
            mRequest.add("parkingName", publishHousing.getText().toString());
            mRequest.add("address", publishParkDq.getText().toString());
            mRequest.add("parkingNumber", publishPlaceNumber.getText().toString());
            mRequest.add("floor", publishPlaceFloor.getText().toString());
            mRequest.add("latitude", lat+"");
            mRequest.add("longitude", lng+"");
            mRequest.add("province", provinceName);
            mRequest.add("city", cityName);
            mRequest.add("area", areaName);

            mRequest.add("name", etName.getText().toString());
            if (radioGroup.getCheckedRadioButtonId() == R.id.man) {
                mRequest.add("sex", "先生");
            } else {
                mRequest.add("sex", "女士");
            }
            mRequest.add("phone", publishPhone);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomJavaHttpListener<BaseJavaBean>(this, true, BaseJavaBean.class) {
                        @Override
                        public void doWork(BaseJavaBean data, int code) {
                            startActivity(new Intent(CarportShareActivity.this,CarportResultActivity.class)
                                    .putExtra("carport_tag",1));
                            finish();
                        }

                        @Override
                        public void onFinally(String obj, int code, boolean isSucceed) throws JSONException {
                            if (code != 0) {
                                ToastUtils.showShort(obj+"");
                            }

                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1007 && resultCode == 1008 && data != null) {
            LatLng latLng = data.getParcelableExtra("location");
            lat = latLng.latitude;
            lng = latLng.longitude;
            cityName = data.getStringExtra("cityName");
            areaName = data.getStringExtra("areaName");
            provinceName = data.getStringExtra("provinceName");
            publishParkDq.setText(data.getStringExtra("address"));
        }
    }
    /**
     * 获取车位类型
     */
    private void getCarPlaceType() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "GetSpaceType");
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<AddStallTypeBean>(baseContext, true, AddStallTypeBean.class) {
                        @Override
                        public void doWork(AddStallTypeBean data, String code) {
                            if ("1".equals(code)) {
                                for (int i = 0; i < data.getData().size(); i++) {
                                    carType1.add(new CarPlaceTypeMode(data.getData().get(i).getKey()
                                            ,data.getData().get(i).getValue()));
                                    ArrayList<CarPlaceTypeMode> type1 = new ArrayList<>();
                                    for (int j = 0; j < data.getData().get(i).getData().size(); j++) {
                                        type1.add(new CarPlaceTypeMode
                                                (data.getData().get(i).getData().get(j).getKey(),data.getData().get(i).getData().get(j).getValue()));
                                    }
                                    carType2.add(type1);
                                }
                                initCustomOptionPicker();
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!code.equals("1")) {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    private void initCustomOptionPicker() {
        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = carType1.get(options1).getValue()+"-"+carType2.get(options1).get(option2).getValue() ;
                typeChoose.setText(tx);
                carPlaceId = carType2.get(options1).get(option2).getKey() +"";
            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        pvCustomOptions.setPicker(carType1,carType2);//添加数据
        pvCustomOptions.show();
    }
}
